/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.MaintainPlanContentEnum;
import org.springblade.modules.repair.enums.TaskStatusEnum;
import org.springblade.modules.repair.mapper.MaintainMalfunctionHistoryMapper;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.MaintainMalfunctionHistoryVO;
import org.springblade.modules.repair.vo.MalFunctionHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 故障工单明细 服务实现类
 *
 * @author BladeX
 * @since 2021-05-21
 */
@Service
public class MaintainMalfunctionHistoryServiceImpl extends BaseServiceImpl<MaintainMalfunctionHistoryMapper, MaintainMalfunctionHistory> implements IMaintainMalfunctionHistoryService {

	@Autowired
	private IMaintainPlanContentService planContentService;
	@Autowired
	private IMaintainPlanContentExtService planContentExtService;
	@Autowired
	private IWxFaultTypeService wxFaultTypeService;
	@Autowired
	private IWxFaultCauseService wxFaultCauseService;

	/**
	 * 状态1：设备检修 2：部件更换
	 */
	private final Integer[] DISPOSE_TYPE = {1, 2};

	@Override
	public IPage<MaintainMalfunctionHistoryVO> selectMaintainMalfunctionHistoryPage(IPage<MaintainMalfunctionHistoryVO> page, MaintainMalfunctionHistoryVO maintainMalfunctionHistory) {
		return page.setRecords(baseMapper.selectMaintainMalfunctionHistoryPage(page, maintainMalfunctionHistory));
	}

	@Override
	public boolean deleteBatch(Long planId, Long checkContentId) {
//        List<MaintainMalfunctionHistory> list = this.list(Wrappers.<MaintainMalfunctionHistory>lambdaQuery().eq(MaintainMalfunctionHistory::getPlanId, planId).eq(MaintainMalfunctionHistory::getCheckContentId, checkContentId));
//        List<Long> ids = list.stream().map(MaintainMalfunctionHistory::getId).collect(Collectors.toList());
//        this.removeByIds(ids);
//        return true;
		return false;
	}

	@Override
	public List<MalFunctionHistoryVO> selectByPlanId(Long planId) {

		Map<Long, List<WxFaultType>> wxFaultTypeMap = wxFaultTypeService.list().stream().collect(Collectors.groupingBy(WxFaultType::getId));
		Map<Long, List<WxFaultCause>> wxFaultCauseMap = wxFaultCauseService.list().stream().collect(Collectors.groupingBy(WxFaultCause::getId));

		List<MalFunctionHistoryVO> malFunctionHistoryVOS = baseMapper.selectByPlanId(planId);
		for (MalFunctionHistoryVO malFunctionHistoryVO : malFunctionHistoryVOS) {
			//封装维修原因
			List<String> names0 = new ArrayList<>(16);
			if (StrUtil.isNotEmpty(malFunctionHistoryVO.getFaultReasonKey())) {
				List<String> list = Func.toStrList(malFunctionHistoryVO.getFaultReasonKey());
				for (String id : list) {
					List<WxFaultCause> wxFaultTypes = wxFaultCauseMap.get(Convert.toLong(id));
					if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
						names0.add(wxFaultTypes.get(0).getFaultName());
					}
				}
			}
			malFunctionHistoryVO.setWxFaultCauseNames(names0);
			//封装维修责任
			List<String> names1 = new ArrayList<>(16);
			if (StrUtil.isNotEmpty(malFunctionHistoryVO.getFaultReasonWhoKey())) {
				List<String> list = Func.toStrList(malFunctionHistoryVO.getFaultReasonWhoKey());
				for (String id : list) {
					List<WxFaultType> wxFaultTypes = wxFaultTypeMap.get(Convert.toLong(id));
					if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
						names1.add(wxFaultTypes.get(0).getName());
					}
				}
			}
			malFunctionHistoryVO.setWxFaultTypeNames(names1);

		}
		return malFunctionHistoryVOS;
	}

	@Override
	public Long updateHistory(MaintainMalfunctionHistory malfunctionHistory) {
		MaintainPlanContent planContent = planContentService.getById(malfunctionHistory.getPlanId());
		MaintainPlanContentExt planContentExt = planContentExtService.getOne(Wrappers.<MaintainPlanContentExt>lambdaQuery().eq(MaintainPlanContentExt::getPlanId, malfunctionHistory.getPlanId()));
		if (planContent.getTypeStatus().equals(MaintainPlanContentEnum.MAINTAIN_WX.getId())) {
			if (!planContent.getStatus().equals(TaskStatusEnum.WX_UNDER_WAY.getStatus())) {
				if (planContent.getStatus().equals(TaskStatusEnum.WX_SIGN_FINISH.getStatus())) {
					long betweenHour = DateUtil.between(planContentExt.getPlanEndTime(), DateUtil.date(), DateUnit.HOUR);
					if (betweenHour > 24) {
						throw new ServiceException("工单状态已变更，请刷新页面");
					}
				} else {
					throw new ServiceException("工单状态已变更，请刷新页面");
				}
			}
		}
		if (!planContent.getStatus().equals(TaskStatusEnum.PARTS_CHANGE.getStatus()) && planContent.getTypeStatus().equals(MaintainPlanContentEnum.MAINTAIN_PARTS.getId())) {
			throw new ServiceException("工单状态已变更，请刷新页面");
		}
		super.saveOrUpdate(malfunctionHistory);
		return malfunctionHistory.getId();
	}

	@Override
	public List<MaintainMalfunctionHistory> listByPlanUser(Long planId, Long userId) {
		return baseMapper.listByPlanUser(planId, userId);
	}

}


